import { useEffect, useRef } from 'react'
import { getInstanceByDom, init } from 'echarts'

type BarChartOptions = {
    xAxisData: Array<string>,
    seriesData: Array<Array<number>>,
};

const BarChart = ({ options }: { options: BarChartOptions }) => {
    const { xAxisData, seriesData } = options;

    // 放置图表的元素
    const chartRef = useRef(null);

    // 初始化图表
    useEffect(() => {
        const myChart = init(chartRef.current);
        // 开始观察
        const observer = new ResizeObserver(() => myChart?.resize());
        observer.observe(chartRef.current!);
        // 结束观察，清理图表
        return () => {
            observer.disconnect();
            myChart.dispose();
        };
    }, []);

    // 更新图表
    useEffect(() => {
        // 获取实例
        const myChart = getInstanceByDom(chartRef.current!);
        // 准备图表参数
        const option = {
            title: { text: '柱状图', textAlign: 'center', top: 8, left: '50%' },
            grid: { left: 40, right: 40, bottom: 40 },
            legend: { width: '100%', height: '100%' },
            xAxis: { type: 'category', data: xAxisData },
            yAxis: { type: 'value' },
            series: seriesData.map(data => ({ data, type: 'bar' })),
        };
        // 渲染参数
        myChart?.setOption(option);
    }, [xAxisData, seriesData]);

    return (
        <div ref={chartRef} style={{ width: '100%', height: '100%' }} />
    );
};

export default BarChart;